package xyz.perkd.util;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DateTimeUtil {
    public static String getLoggerStamp() {
        return "[" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")) + "] ";
    }



    /**
     * 日期偏移
     *
     * @param input  原始内容
     * @param offset 偏移日期天数
     * @return 处理后内容
     */
    public static String offsetDate(String input, int offset) {
//        String input = "Event date: 12/31//23, backup: 01/15//24";
        // 匹配mm/dd//yy格式的正则表达式
        Pattern pattern = Pattern.compile("(\\d{2}/\\d{2}/\\d{2})");
        Matcher matcher = pattern.matcher(input);
        StringBuffer result = new StringBuffer();

        // 创建日期格式化器（处理两位数年份：1950-2049范围）
        DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .appendPattern("MM/dd/")
                .appendValueReduced(ChronoField.YEAR, 2, 2, 1950)
                .toFormatter();

        while (matcher.find()) {
            String matchedDate = matcher.group(1);
            // 移除多余的斜杠（转换mm/dd//yy → mm/dd/yy）
            String normalized = matchedDate.replace("//", "/");

            try {
                // 解析日期并减10天
                LocalDate date = LocalDate.parse(normalized, formatter);
                LocalDate newDate = date.plusDays(offset);

                // 重新格式化为mm/dd/yy
                String formattedDate = newDate.format(formatter);

                // 替换原始匹配内容
                matcher.appendReplacement(result, formattedDate);
            } catch (Exception e) {
                // 解析失败时保留原始内容
                matcher.appendReplacement(result, matchedDate);
            }
        }
        matcher.appendTail(result);

        return result.toString();
    }
}
